package com.changgou.gateway.fileter;

import com.changgou.common.constant.AuthorizeConstant;
import com.changgou.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    /**
     * 1、获取当前请求地址；
     * 2、判断是否登录
     * 2.1、如果是登录请求的话（如果地址中包含/api/user/login /api/user/add），放行；
     * 2.2、如果是非登录请求的话；
     * 2.2.1. 获取请求地址中的令牌
     * 2.2.2. 请求头部获取令牌
     * 2.2.3. 如果没有获取到令牌则返回不能访问
     * 2.2.4. 解析令牌；如果解析报错则说明令牌有问题被人修改或者过期，禁止访问；如果令牌解析正确则放行
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求
        ServerHttpRequest request = exchange.getRequest();
        //获取响应
        ServerHttpResponse response = exchange.getResponse();
        //获取请求地址(访问路径)
        String path = request.getURI().getPath();

        if(!path.startsWith("/api/user/login") && !path.startsWith("/api/user/add")){
            //从请求参数中获取令牌
            String token = request.getQueryParams().getFirst(AuthorizeConstant.AUTHORIZE_TOKEN);

            //从请求头中获取令牌
            if (StringUtils.isEmpty(token)) {
                token = request.getHeaders().getFirst(AuthorizeConstant.AUTHORIZE_TOKEN);
            }
            //从cookie中获取令牌
            if (StringUtils.isEmpty(token)){
                HttpCookie cookie = request.getCookies().getFirst(AuthorizeConstant.AUTHORIZE_TOKEN);
                if (chain!=null){
                    token=cookie.getValue();
                }
            }

            //如果令牌为空则不允许访问
            if (StringUtils.isEmpty(token)) {
                //设置方法不允许
                response.setStatusCode(HttpStatus.METHOD_NOT_ALLOWED);
                return response.setComplete();
            }

            try {

                if (!token.toLowerCase().startsWith("bearer")){
                    //令牌类型为bearer类型，所以在令牌前面加bearer
                    token="bearer"+token;
                }

                //传递令牌
                request.mutate().header(AuthorizeConstant.AUTHORIZE_TOKEN,token);

            } catch (Exception e) {
                e.printStackTrace();
                //未授权
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        //值越小越先执行
        return 0;
    }
}
